<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="用户名称" v-model="listQuery.condition.name">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleDelete" type="primary" icon="el-icon-edit">删除</el-button>
    </div>
      <el-table :key='tableKey' ref="multipleTable" :data="list" v-loading="listLoading"
                element-loading-text="给我一点时间" border fit highlight-current-row
                style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column align="center" label="序号" width="65">
          <template slot-scope="scope">
            <span>{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="编码">
          <template slot-scope="scope">
            <span>{{scope.row.code}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="姓名">
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="手机号">
          <template slot-scope="scope">
            <span>{{scope.row.mobile}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="联系电话">
          <template slot-scope="scope">
            <span>{{scope.row.tel}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="电子邮箱">
          <template slot-scope="scope">
            <span>{{scope.row.email}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="性别">
          <template slot-scope="scope">
            <span>{{scope.row.gender}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="所属部门">
          <template slot-scope="scope">
            <span>{{scope.row.departmentName}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="联系电话">
          <template slot-scope="scope">
            <span>{{scope.row.corpTel}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="220" class-name="small-padding">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="primary" size="mini" @click="handleGrant(scope.row)">授权</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-show="!listLoading" class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.current"
                       :page-sizes="[10,20,30, 50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 400px; margin-left:50px;'>
          <el-form-item label="编码" prop="code">
            <el-input v-model="temp.code" placeholder="请输入机构编码"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="temp.name" placeholder="请输入机构名称"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="temp.mobile"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="temp.tel"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="temp.email"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-input v-model="temp.gender"></el-input>
          </el-form-item>
          <el-form-item label="所属部门" prop="department">
            <el-input v-model="temp.department"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
          <el-button v-else type="primary" @click="updateData">确 定</el-button>
        </div>
      </el-dialog>
    <el-dialog title="授权" :visible.sync="dialogRoleVisible" :before-close="handleClose">
      <el-table key="1" ref="roleMultipleTable" :data="roleList" v-loading="roleListLoading"
                element-loading-text="给我一点时间" border fit highlight-current-row
                style="width: 100%" @selection-change="handleRoleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column align="center" label="序号" width="65">
          <template slot-scope="scope">
            <span>{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="名称">
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="标题">
          <template slot-scope="scope">
            <span>{{scope.row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column width="300px" align="center" label="描述">
          <template slot-scope="scope">
            <span>{{scope.row.description}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantData">确 定</el-button>
      </div>
    </el-dialog>
    </div>
</template>

<script>
  import { queryPage, create, update, deleted, allRole, ownRole, grantRole } from '@/api/sysuser'
  import waves from '@/directive/waves' // 水波纹指令

  export default {
    name: 'org',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        multipleSelection: [],
        listLoading: false,
        total: null,
        listQuery: {
          current: 1,
          size: 10,
          order: '',
          condition: {
            name: undefined
          }
        },
        temp: {
          id: undefined,
          code: '',
          name: '',
          mobile: '',
          tel: '',
          email: '',
          gender: 1,
          department: undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          code: [{ required: true, message: '编码不能为空', trigger: 'change' }],
          name: [{ required: true, message: '名称不能为空', trigger: 'change' }],
          gender: [{ required: true, message: '性别不能为空', trigger: 'change' }]
        },
        roleList: null,
        dialogRoleVisible: false,
        roleListLoading: false,
        userId: undefined,
        roleMultipleSelection: []
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        queryPage(this.listQuery).then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.current = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.current = val
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          code: '',
          name: '',
          mobile: '',
          tel: '',
          email: '',
          gender: 1,
          department: undefined
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            create(this.temp).then(response => {
              this.temp = response.data
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            update(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete() {
        var ids = []
        this.multipleSelection.forEach(function(item, index, array) {
          ids.push(item.id)
        })
        deleted(ids).then(response => {
          if (response.code === 0) {
            for (var i = 0; i < ids.length; i++) {
              this.removeList(ids[i])
            }

            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'fail',
              duration: 2000
            })
          }
        })
      },
      removeList(id) {
        const index = this.list.findIndex(d => d.id === id)
        this.list.splice(index, 1)
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      listAllRole() {
        allRole().then(response => {
          this.roleList = response.data
          this.roleListLoading = false
        })
      },
      handleGrant(row) {
        this.userId = row.id
        this.dialogRoleVisible = true
        if (this.roleList == null) {
          this.listAllRole()
        }
        ownRole(row.id).then(response => {
          var ownIds = response.data

          if (ownIds !== null) {
            for (var i = 0; i < ownIds.length; i++) {
              this.toggleRows(ownIds[i])
            }
          } else {
            this.$refs.roleMultipleTable.clearSelection()
          }
        })
      },
      toggleRows(id) {
        if (this.roleList !== null) {
          for (var i = 0; i < this.roleList.length; i++) {
            if (this.roleList[i].id === id) {
              this.$refs.roleMultipleTable.toggleRowSelection(this.roleList[i])
            }
          }
        }
      },
      grantData() {
        var ids = []
        this.roleMultipleSelection.forEach(function(item, index, array) {
          ids.push(item.id)
        })
        grantRole(this.userId, ids).then(response => {
          if (response.code === 0) {
            this.dialogRoleVisible = false
            this.$notify({
              title: '成功',
              message: '角色分配成功',
              type: 'success',
              duration: 2000
            })
            this.$refs.roleMultipleTable.clearSelection()
          } else {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'fail',
              duration: 2000
            })
          }
        })
      },
      handleRoleSelectionChange(val) {
        this.roleMultipleSelection = val
      },
      handleClose(done) {
        this.$refs.roleMultipleTable.clearSelection()
        done()
      }
    }
  }
</script>

<style scoped>

</style>
